/*
 *  ExportAction.java
 *
 *  Course Project for User Interface Programming I, 2011
 *  Group 19
 *
 *  This program is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU General Public License
 *  as published by the Free Software Foundation; either version 2
 *  of the License, or any later version.
 *
 */
package justdoit.actions;

import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.io.FileWriter;
import javax.swing.AbstractAction;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.KeyStroke;
import javax.swing.table.TableModel;
import justdoit.Startup;
import justdoit.controller.LanguageManager;
import justdoit.controller.IconManager;
import justdoit.view.model.ExcelFileChooserView;

/**
 * This is for performing action of Exporting XML file 
 * when user clicks "Export" item
 *
 * @author Raj
 */
public class ExportAction extends AbstractAction {

    public ExportAction() {
        super(LanguageManager.getString("menu.file.export"), IconManager.getIcon("export.png"));
        putValue(MNEMONIC_KEY, LanguageManager.getMnemonic("mnemonic.menu.file.export"));
        putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke("control S"));
    }

    public ExportAction(String text) {
        super(text);
    }

    public ExportAction(String text, ImageIcon icon) {
        super(text, icon);
    }

    public ExportAction(String text, ImageIcon icon,
            String desc, Integer mnemonic) {
        super(text, icon);
        putValue(SHORT_DESCRIPTION, desc);
        putValue(MNEMONIC_KEY, mnemonic);
    }

    public void actionPerformed(ActionEvent e) {
        // TODO: Action completed.
//        JOptionPane.showMessageDialog(null,
//                "Sorry, This function is not implemented!");
        exportToExcel();
    }

    // @author Rajalakshmi
    public void exportToExcel() {
        TableModel model = Startup.getMainFrame().getTaskListPanel().getTaskTable().getModel();
        FileWriter out;
        try {
//                FileWriter out = new FileWriter("./output.xls");
            out = new FileWriter(new ExcelFileChooserView().getFile());
            for (int i = 0; i < model.getColumnCount(); i++) {
                out.write(model.getColumnName(i).toUpperCase() + "\t");
            }
            out.write("\n");
            for (int i = 0; i < model.getRowCount(); i++) {
                for (int j = 0; j < model.getColumnCount(); j++) {
                    out.write(model.getValueAt(i, j).toString() + "\t");
                }
                out.write("\n");
            }
            out.close();
        } catch (Exception e) {
            System.out.println("Error in exportToExcel " + e.getMessage());
        }
    }
}
